<template>
  <page-meta :page-style="`overflow:${show ? 'hidden' : 'visible'};`" />
  <!-- 处理APP端滚动穿透 -->
  <view class="mt-2 border-b border-gray-200 bg-white p-5">
    <!-- 选择人员标题 -->
    <view class="mb-2 w-full flex items-center justify-between">
      <text class="text-4 text-gray-800 font-500">
        {{ title }}
        <text v-if="props.required" class="text-red-500 font-600">*</text>
      </text>
      <view class="text-base text-blue-500" type="button" @click="selectUsers">
        选择人员
      </view>
    </view>
    <!-- 已选人员列表 -->
    <view v-if="userSelectedList.length > 0" class="selected-users flex flex-wrap gap-2">
      <view
        v-for="user in userSelectedList"
        :key="user.id"
        class="selected-user flex flex-col items-center border border-blue-100 rounded-2 bg-blue-50 p-2"
      >
        <view class="avatar mb-1 h-8 w-8 flex items-center justify-center rounded-full bg-blue-100">
          <text class="text-xs text-blue-600">{{ user.realname?.charAt(0) }}</text>
        </view>
        <text class="text-sm">{{ user.realname }}</text>
      </view>
    </view>
    <!-- 暂无选择 -->
    <view v-else class="text-sm text-gray-400">
      暂无选择
    </view>
    <!-- 用户选择器 -->
    <wd-popup v-model="show" lock-scroll position="bottom" custom-style="border-radius: 12px 12px 0 0;">
      <view class="user-picker">
        <view class="search-bar flex items-center justify-between px-4 py-4 shadow-sm">
          <text class="mb-1 block text-base font-medium">{{ props.title }}</text>
          <view class="text-base text-blue-500" type="button" @click="confirmSelection">
            确定
          </view>
        </view>
        <!-- 用户列表 -->
        <view class="user-list h-[50vh] overflow-auto p-5 pt-0">
          <view
            v-for="user in filteredUsers"
            :key="user.id"
            class="user-item flex items-center border-b border-gray-200 border-b-solid py-5"
            @click="toggleUserSelection(user)"
          >
            <view class="avatar mr-4 h-12 w-12 flex items-center justify-center rounded-full bg-blue-100">
              <text class="text-gray-600">{{ user.realname.charAt(0) }}</text>
            </view>
            <view class="flex-1 overflow-hidden">
              <text class="mb-1 block text-base font-medium">{{ user.realname }}</text>
              <view class="w-full text-sm text-gray-500 text-ellipsis">
                {{ user.departNames }}{{ user.departNames }}
              </view>
            </view>
            <view class="h-6 w-6 border-2 border-blue-400 rounded-2 border-solid px-1 text-blue-600 font-bold line-height-5" :class="{ 'bg-blue-500 border-blue-500 text-white': isUserSelected(user.id) }">
              {{ isUserSelected(user.id) ? '✓' : '' }}
            </view>
          </view>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { computed, onMounted, watch } from 'vue'
import { useSystemStore } from '@/store/system'

interface SimplifiedUser {
  id: string
  username: string
  realname: string
  phone: string
  departIds: string
  departNames: string
  managerUser: boolean
}

const props = withDefaults(defineProps<{
  title?: string
  modelValue?: string[] // v-model 绑定
  multiple?: boolean
  required?: boolean
}>(), {
  title: '选择人员',
  modelValue: () => [], // v-model 默认值
  multiple: true, // 默认支持多选
  required: false, // 默认非必填
})

const emit = defineEmits(['confirm', 'update:modelValue'])

const systemStore = useSystemStore()
const { getSelectUserList } = storeToRefs(systemStore)
const show = ref(false)

// 过滤用户列表
const filteredUsers = computed(() => getSelectUserList.value())

// 获取用户列表数据
const userSelectedList = ref<SimplifiedUser[]>([])

// 检查用户是否被选中
function isUserSelected(userId: string): boolean {
  return userSelectedList.value.some(u => u.id === userId)
}

// 打开选择器
function selectUsers() {
  show.value = true
  console.log(userSelectedList.value)
}

// 确认选择
function confirmSelection() {
  show.value = false
  // 将选择的用户ID列表传递给父组件
  const selectedUserIds = userSelectedList.value.map(u => u.id)
  emit('update:modelValue', selectedUserIds)
  emit('confirm', selectedUserIds)
}

// 监听 props.modelValue 的变化，同步到内部的选择列表
watch(() => props.modelValue, (newModelValue) => {
  if (newModelValue && Array.isArray(newModelValue)) {
    // 根据用户ID查找对应的用户对象
    const allUsers = getSelectUserList.value()
    userSelectedList.value = allUsers.filter(user => newModelValue.includes(user.id))
  }
}, { immediate: true })

// 切换用户选择状态
function toggleUserSelection(user: SimplifiedUser) {
  const index = userSelectedList.value.findIndex(u => u.id === user.id)

  if (index >= 0) {
    // 取消选择
    userSelectedList.value.splice(index, 1)
  }
  else {
    // 如果是单选模式，清空已选择的用户
    if (!props.multiple) {
      userSelectedList.value = []
    }
    // 添加选择
    userSelectedList.value.push(user)
  }
}

// 初始化的时候获取用户列表
onMounted(() => {
  systemStore.fetchDepartUserList({
    pageSize: 1000,
    pageNo: 1,
  })
})
</script>
